package io.jft.doll.ui.address

import android.annotation.SuppressLint
import android.arch.lifecycle.ViewModelProviders
import android.content.Context
import android.os.Bundle
import android.view.View
import android.view.inputmethod.InputMethodManager
import chihane.jdaddressselector.OnAddressSelectedListener
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.g.base.extend.mainIoSchedulers
import com.g.base.extend.progressSubscribe
import com.g.base.extend.setTimeout
import com.g.base.help.postSimpleNotify
import com.g.base.room.entity.UserEntity
import com.g.base.router.RouteExtras
import com.g.base.ui.BaseActivity
import com.google.gson.Gson
import io.jft.doll.R
import io.jft.doll.api.AddressApi
import io.jft.doll.api.apiProvider
import io.jft.doll.databinding.ActivityAddressChangeBinding
import io.jft.doll.event.NotifyUrl
import io.jft.doll.model.viewModel.AddressViewModel
import io.jft.doll.room.entity.common.AddressItemCEntity
import io.jft.doll.router.RouterPage
import io.jft.doll.weidget.AddressSelectDialog

/**
 * Created by G on 2017/8/23 0023.
 */

@Route(path = RouterPage.AddressChangeActivity, extras = RouteExtras.NeedOauth)
class ChangeAddressActivity : BaseActivity<ActivityAddressChangeBinding>() {
    override var hasToolbar: Boolean = true

    @Autowired
    @JvmField
    var addressItem: AddressItemCEntity? = null

    private val addressViewModel by lazy { ViewModelProviders.of(this).get(AddressViewModel::class.java) }
    private val addressItemNotNull by lazy { addressItem?.id?.isNotEmpty() == true }

    private var addressSelectDialog: AddressSelectDialog? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ARouter.getInstance().inject(this)
        setContentView(R.layout.activity_address_change)
        showContentView()
        toolbar.setNavigationIcon(R.drawable.ic_arrow_back_toolbar_24dp)
        toolbar.setNavigationOnClickListener {
            finishAfterTransition()
        }

        if (addressItem == null) addressItem = AddressItemCEntity()
        addressViewModel.createAddressChangeBindModel(addressItem!!)
        //选择收货地址点击
        contentView.addressSelect!!.input.setOnClickListener(this::onSelectAddressClick)
        //新增收货地址 or 修改收货地址
        if (addressItemNotNull) {
            toolbar.title = "修改收货地址"
            createMenu()
        } else {
            toolbar.title = "新增收货地址"
        }
        contentView.data = addressViewModel
        contentView.view = this
    }

    @SuppressLint("CheckResult")
    private fun createMenu() {
        toolbar.inflateMenu(R.menu.address_select)
        toolbar.setOnMenuItemClickListener {
            if (it.itemId == R.id.actionDel) {
                //删除收货地址
                apiProvider.create(AddressApi::class.java)
                        .deleteAddress(addressItem?.id!!)
                        .mainIoSchedulers()
                        .progressSubscribe(
                                showSucceed = {
                                    it.dismiss()
                                    //同步收货地址
                                    postSimpleNotify(NotifyUrl.AddressActivity)
                                    finishAfterTransition()
                                },
                                showError = {
                                    it.dismiss()
                                }
                        )
                return@setOnMenuItemClickListener true
            }
            return@setOnMenuItemClickListener false
        }
    }


    @SuppressLint("CheckResult")
    fun onCommitClick(view: View) {
        if (addressViewModel.canCommit()) {
            apiProvider
                    .create(AddressApi::class.java)
                    .let {
                        if (addressItemNotNull)
                            it.upDateAddress(Gson().toJsonTree(addressItem).asJsonObject)
                        else
                            it.insertAddress(Gson().toJsonTree(addressItem).asJsonObject)
                    }
                    .mainIoSchedulers()
                    .progressSubscribe(
                            {
                                postSimpleNotify(NotifyUrl.AddressActivity)
                            },
                            showSucceed = {
                                it.dismiss()
                                //同步收货地址
                                postSimpleNotify(NotifyUrl.AddressActivity)
                                finishAfterTransition()
                            },
                            showError = { it.dismiss() })

        }
    }

    private fun onSelectAddressClick(view: View) {
        val imm = baseContext.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(view.windowToken, 0)
        //等待键盘关闭 和 点击间隔
        setTimeout(200L) {
            addressSelectDialog = AddressSelectDialog.show(this, OnAddressSelectedListener { province, city, county, _ ->
                addressViewModel.addressSelect.input.set("${province?.name ?: ""} ${city?.name
                        ?: ""} ${county?.name ?: ""}")
                addressItem?.province = province?.name ?: ""
                addressItem?.city = city?.name ?: ""
                addressItem?.district = county?.name ?: ""
                addressItem?.provinceId = province?.id?.toString() ?: ""
                addressItem?.cityId = city?.id?.toString() ?: ""
                addressItem?.districtId = county?.id?.toString() ?: ""
                addressSelectDialog?.dismiss()
            })
        }
    }

    override fun onTokenChange(data: UserEntity?) {
        if (data == null) {
            showContentView()
        } else {
            showNeedOauth()
        }
    }

}